package top.codedance.iotp.tools.serverTool.ui;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import top.codedance.iotp.iot.sdk.StandandService;
import top.codedance.iotp.iot.sdk.po.sync.BaseParam;
import top.codedance.iotp.iot.sdk.po.sync.DeleteDevicceParam;
import top.codedance.iotp.tools.serverTool.ServerToolApplication;
import top.codedance.iotp.tools.terminal.TerminalApplication;
import top.codedance.iotp.tools.terminal.ui.WaitLoading;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.MouseEvent;
import java.net.URL;

/**
 * @author Lenovo
 */
public class DeviceListFrame extends javax.swing.JDialog {
    private WaitLoading waitLoading = new WaitLoading(this);
    private MainFrame mf;
    private StandandService standandService;
    private BaseParam baseParam;
    private JPopupMenu jt_jpJPopupMenu;
    private DefaultTableModel dtm;

    /**
     * Creates new form DeviceListFrame
     */
    public DeviceListFrame(MainFrame mf) {
        super(mf, true);
        this.mf = mf;
        initComponents();

        URL url = Thread.currentThread().getContextClassLoader().getResource("logo.gif");
        ImageIcon icon = new ImageIcon(url);
        setIconImage(icon.getImage());
        createPopupMenu();
        setMinimumSize(new Dimension(1062, 643));
        setLocationRelativeTo(this.mf.getShellFrame());
        setTitle("代码飞舞采控系统-查看设备列表");
        this.standandService = new StandandService(ServerToolApplication.serverConf.getServerHost());
        baseParam = new BaseParam();
        baseParam.setUsername(ServerToolApplication.serverConf.getUsername());
        baseParam.setPassword(ServerToolApplication.serverConf.getPassword());

        initTable();
    }

    private void initTable() {
        String[] columnNames = {"id", "deviceId", "unitName", "registeTime"};
        Object[][] tdata = new Object[0][0];
        dtm = new DefaultTableModel(tdata, columnNames);
        device_jt.setModel(dtm);
    }

    private void createPopupMenu() {
        jt_jpJPopupMenu = new JPopupMenu();
        final JMenuItem deItem = new JMenuItem();
        deItem.setText("  删除  ");
        deItem.setOpaque(true);
        deItem.setBackground(new java.awt.Color(255, 51, 51));
        deItem.setForeground(new java.awt.Color(255, 255, 255));
        deItem.addActionListener((ActionEvent e) -> {
            int i = JOptionPane.showConfirmDialog(DeviceListFrame.this, "确定要删除吗？", "确认框", JOptionPane.YES_NO_OPTION);
            if (i == JOptionPane.OK_OPTION) {
                waitLoading.open();
                TerminalApplication.pool.submit(() -> {
                    try {
                        int selectedIndex = device_jt.getSelectedRow();
                        String id = (String) dtm.getValueAt(selectedIndex, 0);
                        DeleteDevicceParam deleteDevicceParam = new DeleteDevicceParam();
                        deleteDevicceParam.setUsername(baseParam.getUsername());
                        deleteDevicceParam.setPassword(baseParam.getPassword());
                        deleteDevicceParam.setId(id);
                        JSONObject jsonObject = standandService.deleteDevices(deleteDevicceParam);
                        Integer status = jsonObject.getInteger("status");
                        if (status == 200) {
                            JOptionPane.showMessageDialog(rootPane, "删除成功");
                            viewBnActionPerformed(e);
                        } else {
                            JOptionPane.showMessageDialog(rootPane, "请求失败：" + jsonObject.getString("message"));
                        }
                    } catch (Exception ex) {
                        JOptionPane.showMessageDialog(rootPane, "更新失败");
                    } finally {
                        waitLoading.close();
                    }
                });
            }
        });

        JMenuItem editItem = new JMenuItem();
        editItem.setText("  删除并复制  ");
        editItem.addActionListener((ActionEvent e) -> {
            int selectedIndex = device_jt.getSelectedRow();
            JSONObject jo = new JSONObject();
            String id = (String) dtm.getValueAt(selectedIndex, 0);
            jo.put("id", id);
            String deviceId = (String) dtm.getValueAt(selectedIndex, 1);
            jo.put("deviceId", deviceId);
            String registeTime = (String) dtm.getValueAt(selectedIndex, 3);
            jo.put("registeTime", registeTime);
            String unitName = (String) dtm.getValueAt(selectedIndex, 2);
            jo.put("unitName", unitName);
            deItem.doClick();
            AddDeviceFrame adf = new AddDeviceFrame(mf);
            adf.setModifyMode(jo);
            adf.setVisible(true);
        });

        jt_jpJPopupMenu.add(deItem);
        jt_jpJPopupMenu.add(editItem);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        viewBn = new javax.swing.JButton();
        jScrollPane3 = new javax.swing.JScrollPane();
        device_jt = new javax.swing.JTable();
        jb_add = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        viewBn.setText("刷新");
        viewBn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                viewBnActionPerformed(evt);
            }
        });

        device_jt.setModel(new javax.swing.table.DefaultTableModel(
                new Object[][]{
                        {},
                        {},
                        {},
                        {}
                },
                new String[]{

                }
        ));
        device_jt.setToolTipText("");
        device_jt.setRowHeight(30);
        device_jt.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                device_jtMouseClicked(evt);
            }
        });
        jScrollPane3.setViewportView(device_jt);

        jb_add.setText("添加设备");
        jb_add.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jb_addActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(layout.createSequentialGroup()
                                .addContainerGap()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                        .addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 659, Short.MAX_VALUE)
                                        .addGroup(layout.createSequentialGroup()
                                                .addComponent(viewBn)
                                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                                .addComponent(jb_add)
                                                .addGap(0, 0, Short.MAX_VALUE)))
                                .addContainerGap())
        );
        layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(layout.createSequentialGroup()
                                .addGap(8, 8, 8)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                        .addComponent(viewBn, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addComponent(jb_add))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 366, Short.MAX_VALUE)
                                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void viewBnActionPerformed(ActionEvent evt) {//GEN-FIRST:event_viewBnActionPerformed
        waitLoading.open();
        TerminalApplication.pool.submit(() -> {
            try {
                JSONObject jsonObject = standandService.listDevices(baseParam);
                Integer status = jsonObject.getInteger("status");
                if (status == 200) {
                    initTable();
                    JSONArray data = jsonObject.getJSONArray("data");
                    JSONObject tmpJo;
                    for (int i = 0; i < data.size(); i++) {
                        tmpJo = data.getJSONObject(i);
                        dtm.addRow(new Object[]{tmpJo.getString("id"), tmpJo.getString("deviceId"), tmpJo.getString("unitName"), tmpJo.getString("registeTime")});
                    }
                } else {
                    JOptionPane.showMessageDialog(rootPane, "请求失败：" + jsonObject.getString("message"));
                }
            } catch (Exception e) {
                JOptionPane.showMessageDialog(rootPane, "更新失败");
            } finally {
                waitLoading.close();
            }
        });
    }//GEN-LAST:event_viewBnActionPerformed

    private void device_jtMouseClicked(MouseEvent evt) {//GEN-FIRST:event_device_jtMouseClicked
        if (evt.getButton() == MouseEvent.BUTTON3) {
            int focuseRowIndex = device_jt.rowAtPoint(evt.getPoint());
            if (focuseRowIndex == -1) {
                return;
            }
            device_jt.setRowSelectionInterval(focuseRowIndex, focuseRowIndex);
            jt_jpJPopupMenu.show(device_jt, evt.getX(), evt.getY());
        }
    }//GEN-LAST:event_device_jtMouseClicked

    private void jb_addActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jb_addActionPerformed
        AddDeviceFrame adf = new AddDeviceFrame(mf);
        adf.setVisible(true);
    }//GEN-LAST:event_jb_addActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTable device_jt;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JButton jb_add;
    private javax.swing.JButton viewBn;
    // End of variables declaration//GEN-END:variables
}
